package at.fhooe.ems.dal;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import at.fhooe.ems.util.DataUtil;

public class Persistence {
	
	
	public int insertSensorData(SensorDataModel data, List<String> activeSensors){
	 int done = 0;
	 ArrayList <String> list=(ArrayList<String>) activeSensors;
	 String sqlQueryBegin="";
	 if(list==null){
		 sqlQueryBegin = "insert into ems3000 (sensor_time,temperature,humidity,smoke,lightness,noise) " +
		 		"values('"+data.getSensorDateTime()+"',NULL,NULL,NULL,NULL,NULL)";
	 }
	 else{
		 
		for(String s:list){
			//System.out.println(s+" "+data.getTemperature());
			sqlQueryBegin="";
			sqlQueryBegin = "insert into ems3000 (sensor_time,temperature,humidity,smoke,lightness,noise) values('"+data.getSensorDateTime()+"'";
    	 if(list.contains("Temperature")){
    		 sqlQueryBegin += ",'"+data.getTemperature()+"'";
    	 }else{
    		 sqlQueryBegin += ","+"NULL";
    	 }
    	 if(list.contains("Humidity")){
    		 sqlQueryBegin += ",'"+data.getHumidity()+"'";
    	 }else{
    		 sqlQueryBegin += ","+"NULL";
    	 }
    	 if(list.contains("Smoke")){
    		 sqlQueryBegin += ",'"+data.getSmokeConstant()+"'";
    	 }else{
    		 sqlQueryBegin += ","+"NULL";
    	 }
    	 if(list.contains("Light")){
    		 sqlQueryBegin += ",'"+data.getLightness()+"'";
    	 }else{
    		 sqlQueryBegin += ","+"NULL";
    	 }
    	 if(list.contains("Noise")){
    		 sqlQueryBegin += ",'"+data.getNoise()+"'";
    	 }else{
    		 sqlQueryBegin += ","+"NULL";
    	 }
    	 sqlQueryBegin+=")";
     }

	 }
	 	System.out.println(sqlQueryBegin);
	 	DBConnector.connectDb();
	    done=DBConnector.processDML(sqlQueryBegin);
	    DBConnector.closeDb();
	    return done;
	}
	
	public ArrayList<ClientResponseModel> getSensorDataForTimePeriod(ClientRequestModel request){
		ArrayList<ClientResponseModel> recordList=new ArrayList<ClientResponseModel>();
		String sqlQuery="SELECT "+request.getType()+
						",sensor_time FROM ems3000 WHERE sensor_time BETWEEN '"+request.getDateFrom()+
						"' AND '"+request.getDateTo()+"' ORDER BY sensor_time";
		try{
		DBConnector.connectDb();
		ResultSet rs = DBConnector.processSQuery(sqlQuery);
		while(rs.next()){
			ClientResponseModel model=new ClientResponseModel();
			model.setType(request.getType());
			model.setValue(rs.getString(1));
			model.setRecordDateTime(DataUtil.converDateToString(rs.getTimestamp(2)));
			recordList.add(model);		
		 }
		 DBConnector.closeDb();
		}
		catch (Exception e){
			e.printStackTrace();
		}
		
		return recordList;
	}
	

}
